import React from 'react'
import PropTypes from 'prop-types'
import moment from 'moment'
import { rule } from 'postcss'
import { LanguageType , SwiftCode } from 'utils/enums'
import { Form, Input, Row, Col, Button, Icon, Radio, DatePicker, Select, InputNumber } from 'antd'
import { converDate, strFormat, strSplit } from 'utils'
import { connect } from 'dva'
import { routerRedux } from 'dva/router'
import styles from '../../themes/detail.less'

const FormItem = Form.Item
const ButtonGroup = Button.Group
const RadioGroup = Radio.Group
const Option = Select.Option
const { TextArea } = Input
const formItemLayout = {
  labelCol: {
    span: 12,
  },
  wrapperCol: {
    span: 12,
  },
}
const AccountFormItemLayout = {
  labelCol: {
    span: 6,
  },
  wrapperCol: {
    span: 18,
  },
}

const ColProps = {
  span: 8,
  style: {
    marginBottom: 0,
  },
}
const AccountColProps = {
  span: 16,
  style: {
    marginBottom: 0,
  },
}

const ButtonProps = {
  size: 'large',
  style: {
    marginBottom: 0,
  },
}
const AccoutDetail = ({
  accoutDetail,
  dispatch,
  loading,
  form: {
    getFieldDecorator,
    validateFields,
    getFieldsValue,
    setFieldsValue,
  },
}) => {
  const dateFormat = 'DD/MM/YYYY'
  const item = accoutDetail.data
  const { accoutTypeData, currenciesTypeData, editType, parentId, chnInstitutionData } = accoutDetail
  let { hintOptions } = accoutDetail
  const handleOk = () => {
    validateFields((errors) => {
      if (errors) {
        return
      }
      let fieldValue = getFieldsValue()
      let institutionName
      let { languageType, account, institutionNameLocal, institutionNameChn } = fieldValue
      if (languageType == LanguageType.LANGUAGE_CHN) {
        institutionName = institutionNameChn
      } else if (languageType == LanguageType.LANGUAGE_LOCAL) {
        institutionName = institutionNameLocal
      }
      fieldValue.nonBankInstitution = '2'
      fieldValue.codeOrSwift = '0'
      account = strSplit(account)
      const data = {
        ...fieldValue,
        account,
        institutionName,
        id: item.id || 1,
        customerId: parentId,
      }
      dispatch({
        type: `accoutDetail/${editType}`,
        payload: {
          ...data,
        },
      })
    })
  }

  const handlecodeOrSwiftChange = (e) => {
    const payload = { codeOrSwift: e.target.value }
    const m = { ...item, ...payload }
    dispatch({
      type: 'accoutDetail/updateState',
      payload: {
        data: {
          ...m,
        },
      },
    })
  }

  const handleBalanceChange = (e) => {
    const payload = { balanceFlag: e.target.value }
    const m = { ...item, ...payload }
    dispatch({
      type: 'accoutDetail/updateState',
      payload: {
        data: {
          ...m,
        },
      },
    })
  }

  const onSign = () => {
    dispatch(routerRedux.push({
      pathname: `/signatory/${item.id}`,
    }))
  }

  const handleLanguageSelect = (value) => {
    const payload = { languageType: value }
    const m = { ...item, ...payload }
    dispatch({
      type: 'accoutDetail/updateState',
      payload: {
        data: {
          ...m,
        },
      },
    })
  }
  const swiftCodeChange = (value) => {
    const inputValue = value.target.value
    if (inputValue in SwiftCode) {
      setFieldsValue({
        swift: SwiftCode[inputValue].SwiftCode,
      })
    }
  }
  const codeOrSwiftUI = () => {
    // if (item.codeOrSwift == '1') {
    //   return (<Col {...ColProps} >
    //     <FormItem label="InstitutionCode" hasFeedback {...formItemLayout}>
    //       {getFieldDecorator('institutionCode', {
    //         initialValue: item.institutionCode || '',
    //       })(<Input />)}
    //     </FormItem>
    //   </Col>)
    // }
    return (<Col {...ColProps} >
      <FormItem label="SwiftCode" hasFeedback {...formItemLayout}>
        {getFieldDecorator('swift', {
          initialValue: item.swift || '',
          rules: [
            {
              required: true,
            },
          ],
        })(<Input />)}
      </FormItem>
    </Col>)
  }
  const SelectProps = {
    showSearch: true,
    optionFilterProp: 'children',
    filterOption: (input, option) => {
      return option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },

  }
  // const InputProps = {
  //   onChange: (value) => {
  //     // let key = value
  //     // hintOptions = []
  //     // value = strFormat(value)
  //     // if (value.length === 0) {
  //     //   key = ''
  //     // }
  //     // const option = <Option key={key} value={value}>{value}</Option>
  //     // hintOptions[0] = option
  //     // dispatch({
  //     //   type: 'accoutDetail/updateState',
  //     //   payload: {
  //     //     hintOptions,
  //     //   },
  //     // })
  //   },
  // }
  const accoutTypeOption = accoutTypeData.map(d => <Option key={d.code}>{d.name}</Option>)
  const currenciesTypeOption = currenciesTypeData.map(d => <Option key={d.code}>{d.code}</Option>)
  const chnInstitutionDataOption = chnInstitutionData.map(d => <Option key={d.code}>{d.name}</Option>)
  const languageOption = [{ key: '0', value: 'English' }, { key: '1', value: '人民币账号' }].map(d => <Option key={d.key}>{d.value}</Option>)
  return (
    <Form layout="horizontal">
      <div className={styles.div_buttonGroup}>
        <ButtonGroup {...ButtonProps}>
          <Button onClick={handleOk} loading={loading.effects['accoutDetail/update']}>
            Save<Icon type="save" />
          </Button>
        </ButtonGroup>
      </div>
      <div className={styles.div_form}>
        <Row >
          <Col {...ColProps} >
            <FormItem label="Language" hasFeedback {...formItemLayout}>
              {getFieldDecorator('languageType', {
                initialValue: item.languageType || '0',
                rules: [
                  {
                    required: true,
                  },
                ],
              })(<Select style={{ width: '100%' }} {...SelectProps} onChange={handleLanguageSelect}>{languageOption}</Select>)}
            </FormItem>
          </Col>
          <Col {...AccountColProps} >
            <FormItem label="AccountNumber" hasFeedback {...AccountFormItemLayout}>
              {getFieldDecorator('account', {
                initialValue: item.account,
                rules: [
                  {
                    required: true,
                  },
                ],
              })(
                <Input />
                // <Select {...SelectHint}>{hintOptions}</Select>
              )}
            </FormItem>
          </Col>
        </Row>
        {item.languageType === '1' &&
          <Row gutter={8}>
            <Col {...ColProps}>
              <FormItem label="户名" {...formItemLayout} >
                {getFieldDecorator('accountNameCN', {
                  initialValue: item.accountNameCN || '',
                  rules: [{
                    required: true,
                  }],
                })(<Input />)}
              </FormItem>
            </Col>
            <Col {...ColProps}>
              <FormItem label="开户银行" {...formItemLayout}>
                {getFieldDecorator('institutionNameCN', {
                  initialValue: item.institutionNameCN || '',
                  rules: [{
                    required: true,
                  }],
                })(<Input />)}
              </FormItem>
            </Col>
            <Col {...ColProps}>
              <FormItem label="开户行地址" {...formItemLayout} >
                {getFieldDecorator('branchCN', {
                  initialValue: item.branchCN || '',
                  rules: [{
                    required: true,
                  }],
                })(<Input />)}
              </FormItem>
            </Col>
          </Row>
        }
        <Row gutter={8}>
          <Col {...ColProps} >
            <FormItem label="AccountType" hasFeedback {...formItemLayout}>
              {getFieldDecorator('personalAccountType', {
                initialValue: item.personalAccountType || 'G',
                rules: [
                  {
                    required: true,
                  },
                ],
              })(<Select style={{ width: '100%' }} {...SelectProps}>{accoutTypeOption}</Select>)}
            </FormItem>
          </Col>
          <Col {...ColProps} >
            <FormItem label="AccountName" hasFeedback {...formItemLayout}>
              {getFieldDecorator('accountName', {
                initialValue: item.accountName,
                rules: [
                  {
                    required: true,
                  },
                ],
              })(<Input />)}
            </FormItem>
          </Col>
          {item.languageType === '1' ?
            <Col {...ColProps} >
              <FormItem label="InstitutionName" hasFeedback {...formItemLayout}>
                {getFieldDecorator('institutionNameChn', {
                  initialValue: item.institutionNameChn,
                })(<Select style={{ width: '100%' }} {...SelectProps}>{chnInstitutionDataOption}</Select>)}
              </FormItem>
            </Col> : <Col {...ColProps} >
              <FormItem label="InstitutionName" hasFeedback {...formItemLayout}>
                {getFieldDecorator('institutionNameLocal', {
                  initialValue: item.institutionNameLocal,
                })(<Input onChange={swiftCodeChange} />)}
              </FormItem>
            </Col>
          }
        </Row>
        <Row gutter={8}>
          <Col {...ColProps} >
            <FormItem label="Branch" hasFeedback {...formItemLayout}>
              {getFieldDecorator('branch', {
                initialValue: item.branch,
                rules: [
                  {
                    required: true,
                  },
                ],
              })(<TextArea rows={2} />)}
            </FormItem>
          </Col>
          {codeOrSwiftUI()}
          <Col {...ColProps} >
            <FormItem label="CurrencyCode" hasFeedback {...formItemLayout}>
              {getFieldDecorator('currencyCode', {
                initialValue: item.currencyCode,
                rules: [
                  {
                    required: true,
                  },
                ],
              })(<Select style={{ width: '100%' }} {...SelectProps}>{currenciesTypeOption}</Select>)}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={8}>
          <Col {...ColProps} >
            <FormItem label="Balance" hasFeedback {...formItemLayout}>
              {getFieldDecorator('balanceFlag', {
                initialValue: item.balanceFlag || '0',
              })(<RadioGroup onChange={handleBalanceChange}><Radio value={'1'}>Yes</Radio><Radio value={'0'}>No</Radio></RadioGroup>)}
            </FormItem>
          </Col>
          <Col {...ColProps} >
            <FormItem label="StatusCode" hasFeedback {...formItemLayout}>
              {getFieldDecorator('statusCode', {
                initialValue: item.statusCode,
              })(<Input />)}
            </FormItem>
          </Col>

          <Col {...ColProps} >
            <FormItem label="beneficiary" hasFeedback {...formItemLayout}>
              {getFieldDecorator('beneficiary', {
                initialValue: item.beneficiary,
              })(<Input />)}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={8}>
          <Col {...ColProps} >
            <FormItem label="IBAN" hasFeedback {...formItemLayout}>
              {getFieldDecorator('iban', {
                initialValue: item.iban,
                rules: [
                  {
                    // required: true,
                  },
                ],
              })(<Input />)}
            </FormItem>
          </Col>
          <Col {...ColProps} >
            <FormItem label="ClientNumber" hasFeedback {...formItemLayout}>
              {getFieldDecorator('clientNumber', {
                initialValue: item.clientNumber,
              })(<Input />)}
            </FormItem>
          </Col>
          <Col {...ColProps} >
            <FormItem label="opened" hasFeedback {...formItemLayout}>
              {getFieldDecorator('opened', {
                initialValue: item.opened ? moment(converDate(item.opened), dateFormat) : '',
              })(<DatePicker style={{ width: '100%' }} format={dateFormat} />)}
            </FormItem>
          </Col>
          <Col {...ColProps} >
            <FormItem label="closed" hasFeedback {...formItemLayout}>
              {getFieldDecorator('closed', {
                initialValue: item.closed ? moment(converDate(item.closed), dateFormat) : '',
              })(<DatePicker style={{ width: '100%' }} format={dateFormat} />)}
            </FormItem>
          </Col>
          <Col {...ColProps} >
            <FormItem label="beneficiaryComment" hasFeedback {...formItemLayout}>
              {getFieldDecorator('beneficiaryComment', {
                initialValue: item.beneficiaryComment,
              })(<TextArea rows={1} />)}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={8}>
          { item.balanceFlag === '1' ? <Col {...ColProps} >
            <FormItem label="Balance" hasFeedback {...formItemLayout}>
              {getFieldDecorator('balance', {
                initialValue: item.balance,
                rules: [
                  {
                    required: true,
                  },
                ],
              })(<InputNumber min={0.0} width="100%" />)}
            </FormItem>
          </Col> : <Col />}
          { item.balanceFlag === 1 ? <Col {...ColProps} >
            <FormItem label="DateOfBalance" hasFeedback {...formItemLayout}>
              {getFieldDecorator('balanceDate', {
                initialValue: item.balanceDate ? moment(item.balanceDate) : '',
              })(<DatePicker style={{ width: '100%' }} />)}
            </FormItem>
          </Col> : <Col />}
          <Col {...ColProps} >
            <FormItem label="Comments" hasFeedback {...formItemLayout}>
              {getFieldDecorator('comments', {
                initialValue: item.comments,
              })(<TextArea rows={4} />)}
            </FormItem>
          </Col>
        </Row>
      </div>
    </Form>

  )
}

AccoutDetail.propTypes = {
  form: PropTypes.object.isRequired,
  dispatch: PropTypes.func,
  loading: PropTypes.object,
  accoutDetail: PropTypes.object,
}

export default connect(({ accoutDetail, loading }) => ({ accoutDetail, loading }))(Form.create()(AccoutDetail))

